package com.itmei.sms.global;

import com.itmei.sms.exception.ServiceException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author itmei
 * @Date 2023/2/7 15:21
 * @description: 全局异常捕获类
 * @Title: GlobalExceptionAdvice
 * @Package com.itmei.sms.global
 */
@ControllerAdvice
public class GlobalExceptionAdvice {

    /**
     * 捕获自己定义的异常
     * @param e
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public ResponseEntity handlerServiceException(ServiceException e){
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorMessage(e.getCode(),e));
    }

    /**
     * 捕获运行时异常
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResponseEntity handlerRuntimeException(RuntimeException e){
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorMessage(e));
    }

    /**
     * 最大的捕获，当切面的捕获处理不了那么就会被该方法捕获
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResponseEntity handlerException(Exception e){
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorMessage(e));
    }
    /**
     * 返回错误信息和报错类的行数
     * @param t
     * @return
     */
    public Map<String, Object> errorMessage (Throwable t){

        Map<String, Object> map = new HashMap<>();
        map.put("errorMsg",t.getMessage());
        map.put("errorClazz",errorClazz(t));
        return map;
    }
    public Map<String, Object> errorMessage (Integer code,Throwable t){
        Map<String, Object> map = new HashMap<>();
        map.put("errorMsg",t.getMessage());
        map.put("errorCode",code);
        return map;
    }

    /**
     * 报错类的行数
     * @param t
     * @return
     */
    public String errorClazz(Throwable t){
        //堆栈跟踪元素数组
        StackTraceElement[] stackTraceElements = t.getStackTrace();
        String exceptionClassTotalName = stackTraceElements[0].toString();
        StackTraceElement[] var6 = stackTraceElements;
        int var7 = stackTraceElements.length;

        for(int var8 = 0; var8 < var7; ++var8) {
            StackTraceElement stackTraceElement = var6[var8];
            //获取含包名称行就是日志打印报错的行数
            if (stackTraceElement.toString().contains("com.itmei")) {//填写自己的包名称
                //出现报错类的行数位置
                exceptionClassTotalName = stackTraceElement.toString();
                break;
            }
        }
        return exceptionClassTotalName;
    }
}
